package com.example.demo.controller;

import com.example.demo.service.CustomerService;
import com.example.demo.pojo.Book;
import com.example.demo.pojo.Customer;
import com.example.demo.pojo.User;
import com.example.demo.service.BookService;
import com.example.demo.service.CustomerService;
import com.example.demo.service.UserService;
import com.example.demo.utils.MailUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@ComponentScan
public class CustomerController {
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Autowired
    private MailUtil mailUtil ;

    @Transactional
    @RequestMapping("/User/getCustByCustNum")
    @ResponseBody
    public String getCustByCustNum(Model model) {
        Customer customer= customerService.getCustByCustNum();
        model.addAttribute("customer",customer);
        return "getCustByCustNum,ok";
    }

    @Transactional
    @RequestMapping("/User/updateCustByCustNum")
    @ResponseBody
    public String updateCustByCustNum(String custNum, String username) {
        int flag =  customerService.updateCustByCustNum(custNum,username);
        if (flag ==1)
            return "updateCustByCustNum,ok";
        else
            return "修改失败";
    }
    @Transactional
    @RequestMapping("/User/addCustByUser")
    @ResponseBody
    public String addCustByUser(String custName, String username, String custNum, int custPhone, String sex, int roomID, int custState) {
        int flag = customerService.addCustByUser(custName,username,custNum,custPhone,sex,roomID,custState);
        if (flag ==1)
            return "addCustByUser,ok";
        else
            return "add失败";
    }

    @Transactional
    @RequestMapping("/Admin/updateCustUserNameByUserID")
    @ResponseBody
    public String updateCustUserNameByUserID(int userID, String username) {
        int flag =  customerService.updateCustUserNameByUserID(userID,username);
        if (flag ==1)
            return "updateCustByCustNum,ok";
        else
            return "修改失败";
    }
    @Transactional
    @RequestMapping("/Admin/getCustAll")
    @ResponseBody
    public String getCustAll(Model model) {
        List<Customer> customerList =customerService.getCustAll();
        return "get customerList,ok";
    }
    @Transactional
    @RequestMapping("/Admin/deleteCustByCustID")
    @ResponseBody
    public String deleteCustByCustID(int custID) {
        int flag = customerService.deleteCustByCustID(custID);
        if (flag ==1)
            return "deleteCustByCustID,ok";
        else
            return "deleteCustByCustID,失败";
    }
    @Transactional
    @RequestMapping("/Admin/updateCustNameByCustID")
    @ResponseBody
    public String updateCustNameByCustID(int custID, String custName, String username, String custNum, int custPhone, String sex, int roomID, int custState) {
        int flag = customerService.updateCustNameByCustID(custID,custName,username,custNum,custPhone,sex,roomID,custState);
        if (flag ==1)
            return "updateCustByCustNum,ok";
        else
            return "修改失败";
    }


    /**
     * 客户信息查看
     * 如果没有写真实姓名就跳转到添加顾客信息
     * 已完善信息则显示客户信息，可进行修改操作
     *
     * @return
     */
    @Transactional
    @RequestMapping(value = "/user-information", method = RequestMethod.GET)
    public String getinformation(HttpSession session, Map map) {
        String username = String.valueOf(session.getAttribute("username"));
        User user = userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        if (customer== null) {
            map.put("customer",customer);
            map.put("msg","没有客户信息,请先添加客户信息");
            return "user-addCust";
        } else {
            session.setAttribute("customer",customer);
            map.put("getCustName",customer.getCustName());
            map.put("email",user.getEmail());
            map.put("customer", customer);
            session.setAttribute("user",user);
            return "user-information";
        }

    }

    //添加顾客信息页面
    @Transactional
    @RequestMapping(value = "/user-addCust", method = RequestMethod.GET)
    public String getaddCust(HttpSession session, Map remap) {
        String username = String.valueOf(session.getAttribute("username"));
        User user = userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        if(customer==null){
            remap.put("msg","填写信息");
            return "user-addCust";
        }
        else  {
            remap.put("getCustName",customer.getCustName());
            remap.put("msg3","已有用户信息,可前往个人信息管理处修改信息");
            return "user-addCust";
        }
    }

    //添加顾客信息
    @Transactional
    @RequestMapping(value = "/user-addCust", method = RequestMethod.POST)
    public Map<String,Object>addCust(Customer customer,  HttpSession session) {
        Map<String,Object >remap =new HashMap<>();
        String username = String.valueOf(session.getAttribute("username"));
        User user = userService.getUserByUsername(username);
        int uID = user.getuID();
        if (StringUtils.isEmpty(customer.getCustName())) {
            remap.put("msg", "姓名不能为空");
            return remap;
        }
        if (StringUtils.isEmpty(customer.getCustNum())) {
            remap.put("msg", "身份号不能为空");
            return remap;
        }
        if (StringUtils.isEmpty(customer.getSex())) {
            remap.put("msg", "性别不能为空");
            return remap;
        }
        if (StringUtils.isEmpty(String.valueOf(customer.getCustPhone()))) {
            remap.put("msg", "手机号不能为空");

            return remap;
        }
        if(customerService.checkCustNumIfexit(customer.getCustNum()) != null) {
            remap.put("msg", "该证件号已登记");
            return remap;
        }else {
            customerService.addCustMsg(customer.getCustName(), uID, customer.getCustNum(), customer.getCustPhone(), customer.getSex());
            remap.put("getCustName","已有用户信息,可前往个人信息管理处修改信息");
            remap.put("msg", "添加成功，可前往个人信息管理处修改信息");
            return remap;
        }

    }

    /**
     * 弹出层表单 客户修改个人信息
     * @return
     */
    @Transactional
    @RequestMapping(value = "/toUser-updateCust", method = RequestMethod.GET)
    public String getupdateCust(HttpSession session,Map map) {
        String username = (String) session.getAttribute("username");
        User user = userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        map.put("customer",customer);

        return "user-updateCust";

    }
    @Transactional
    @RequestMapping(value = "/user-updateCust", method = RequestMethod.POST)
    @ResponseBody
    public  ModelAndView updateCust(Customer customer, HttpSession session){
        ModelAndView modelAndView =new ModelAndView();
        User user =(User) session.getAttribute("user");
        customer.setuID(user.getuID());

        if(customerService.checkCustNumIfexit(customer.getCustNum()) == null) {
            try{
                customerService.update(customer);
                modelAndView.setViewName("user-updateCust1");
                modelAndView.addObject("msgg","success");
            }catch (Exception e){
                System.out.println("修改失败");
                modelAndView.addObject("msgg","fail");
                modelAndView.setViewName("user-updateCust1");
            }
        }else{
            System.out.println("修改失败，证件号重复");
            modelAndView.addObject("msgg","fail");
            modelAndView.setViewName("user-updateCust1");
        }

        return modelAndView;
    }
    @Transactional
    @GetMapping("/toBookList")
    public String toBookList(HttpSession session)
    {
        String username = (String) session.getAttribute("username");
        Map<String, Object> map = new HashMap<>();
        User user = userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        if (customer == null) {

            map.put("customer", customer);
            map.put("msg", "没有客户信息,请先添加客户信息");
            return "user-addCust";
        }
        return "user-book-list";
    }

    /**
     * 客户预订单查看
     */
    @Transactional
    @RequestMapping(value = "/user-book-list",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object>  getbooklist(HttpSession session,int page,int limit) {
        String username = (String) session.getAttribute("username");
        Map<String, Object> map = new HashMap<>();
        User user = userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        int custID = customer.getCustID();
        List<Book> books = bookService.findByAll(custID);//找出该用户全部订单
        PageHelper.startPage(page,limit);
        List<Book>book = bookService.findByBook(custID);//每页显示的订单
        map.put("code", 0);
        map.put("msg", "");
        map.put("count",books.size());
        map.put("data",book);
        return map;
    }

    /**
     * 修改个人密码
     */
    @RequestMapping(value = "/user-updatepassword",method = RequestMethod.GET)
    public String userpassword(){
        return "user-updatepassword";
    }
    @Transactional
    @RequestMapping(value = "/user-updatepassword",method = RequestMethod.POST)
    public String updatepassword(@RequestParam("old_password")String old_password,@RequestParam("new_password")String new_password,
                                 @RequestParam("renew_password")String renew_password,Map map,HttpSession session){
        String username = (String) session.getAttribute("username");
        User user =userService.getUserByUsername(username);
        if(!old_password.equals(user.getPassword())){
            map.put("msg","原密码错误！");
            return "user-updatepassword";
        }
        if(new_password.equals(user.getPassword())){
            map.put("msg","新密码与原密码相同！");
            return "user-updatepassword";
        }
        if(!new_password.equals(renew_password)){
            map.put("msg","两次密码不相同");
            return "user-updatepassword";
        }
        else {
            userService.updatePasswordByUsername(username,new_password);
            map.put("msg","修改成功！");
            return "user-updatepassword";
        }
    }
    @Transactional
    @RequestMapping(value = "/user-deletebook",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> deletebook(String out_trade_no){
        Map<String,Object> remap =new HashMap<>();
        try{
            bookService.deleteBook(out_trade_no);
            remap.put("msg","成功");
        }catch ( Exception e){
            System.out.println("失败");
        }finally {
            return remap;
        }
//            bookService.deleteBook(out_trade_no);
//            remap.put("suc","200");
//            return  remap;
    }

    @RequestMapping(value = "/user-toupdateEmail",method = RequestMethod.POST)
    @ResponseBody
    public String  toupdateEamil(HttpSession session){
        String username = (String) session.getAttribute("username");
        String email =(String) session.getAttribute("email");
        try{
            userService.updateEmailByUsername(username,email);
            return "ok";
        }catch (Exception e){
            System.out.println("失败");
            return "";
        }
    }

    @RequestMapping(value = "/user-updateEmail",method = RequestMethod.GET)
    @ResponseBody
    public String updateEamil(String email,HttpSession session){
        String getemailcode=mailUtil.getCheckCode(email);
        session.setAttribute("email",email);
        return getemailcode;

    }


}
